package wodegua.d23_test.demo4;

import java.util.Arrays;
import java.util.Objects;

public class MyArrayList<E> {
    private Object[] elementData;
    private int size;
    private final int DEFAULT_CAPACITY = 10;

    public MyArrayList() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    public void add(E e){
        if (size == elementData.length) {
            elementData = Arrays.copyOf(elementData, elementData.length + (DEFAULT_CAPACITY >> 1));
        }
        elementData[size++] = e;
    }

    public E get(int index) {
        checkIndex(index);
        return (E) elementData[index];
    }

    public E remove(int index) {
        checkIndex(index);
        E e = (E) elementData[index];
        System.arraycopy(elementData,index + 1, elementData, index, size - index - 1);
        elementData[--size] = null;
//        Object[] newObjects = new Object[elementData.length];
//        int newIndex = 0;
//        for (int i = 0; i < size; i++) {
//            if (i == index) {
//                continue;
//            }
//            newObjects[newIndex++] = elementData[i];
//        }
//        elementData = newObjects;
//        --size;
        return e;
    }

    public int size(){
        return size;
    }

    public void forEach(MyConsumer<E> e){
        Objects.requireNonNull(e);
        for (int i = 0; i < size; i++) {
            e.accept((E) elementData[i]);
        }
    }

    private void checkIndex(int index){
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException(index + " out of max length " + size);
        }
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        s.append("[");
        for (int i = 0; i < size; i++) {
            E e = (E) elementData[i];
            s.append(i != 0 ? ", " : "");
            s.append(i);
            s.append(e);
        }
        s.append("]");
        return s.toString();
    }
}
